package cn.z2huo.knowledge.concurrency.lock.reentrantlock.interrupt;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Getter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 *
 * @author z2huo
 */
class IncrementData {

    @Getter
    public int sum = 0;

    private final ReentrantLock lock;

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    public IncrementData(ReentrantLock lock) {
        this.lock = lock;
    }

    public void increase() {
        sum++;
    }

    public void lockInterruptiblyAndFastIncrease(String threadName) {
        // todo 在这里输出抢占锁的开始是不合适的，在 lock 方法内部，线程创建队列节点并拼接链表时，才算当前线程抢占锁成功
//        executorService.execute(() -> System.out.println("线程：" + threadName + " run"));
        System.out.println("线程：" + threadName + " run");
        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            System.err.println("线程：" + threadName + " 抢锁失败，被中断");
            return;
        }

        try {
            System.out.println("线程：" + threadName + " 抢到了锁");
//            executorService.execute(() -> System.out.println("线程：" + threadName + " 抢到了锁"));
            ThreadUtil.sleep(1000);
            sum++;
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("线程：" + threadName + " 被中断");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
